
function divEscapedContentElement(message) {
    return $('<div></div>').text(message);
}
function divSystemContentElement(message) {
    return $('<div></div>').html('<i>' + message + '</i>');
}

function processUserInput(chatApp,socket){
    var input = $("#send-message");
    var showview = $(".messages");
    var message = input.val();
    var systemMessage;
    if(message.charAt(0) == "/") {
        systemMessage = chatApp.processCommand(message);
        if(systemMessage) {
            showview.append(divSystemContentElement(systemMessage));
        }
    }else {
        chatApp.sendMessage($("header").text(),message);
        showview.append(divEscapedContentElement(" I: " + message));
        showview.scrollTop(showview.prop("scrollHeight"));

    }
    input.val("");
}

var socket = io.connect();

$(function(){
    var chatApp = new Chat(socket);
    var showview = $(".messages");
    socket.on("nameResult",function(result){
        var message;
        if(result.success){
            message = "You are now known as " + result.name +".";
        }else {
            message = result.message;
        }
        showview.append(divSystemContentElement(message));
    });

    socket.on("joinResult",function(result){
        $("header").text(result.room);
        showview.append(divSystemContentElement("Room changed to " + result.room +". "));
    });

    socket.on("message",function(message){
        if(message.type == "sys"){
            showview.append(divSystemContentElement(message.text));
        }else{
            showview.append(divEscapedContentElement(message.text));
        }
    });

    socket.on("rooms",function(rooms){
        var roomlist = $(".roomList");
        roomlist.empty();
        for (var room in rooms){
            room = room.substring(1,room.length);
            if (room != "") {
                roomlist.append(divEscapedContentElement(room));
            }
        }
        roomlist.find("div").click(function () {
            chatApp.processCommand("/join " + $(this).text());
            $("#send-message").focus();
        });
    });

    setInterval(function(){
        socket.emit("rooms");
    },1000);

    $("#send-form").submit(function(e){
        e.preventDefault();
        processUserInput(chatApp,socket);
        return false;
    });

    window.onbeforeunload = function(){
        socket.emit("disconnect");
    }
});